package com.dongwu.manager.web;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.web.BaseController;
import com.dongwu.manager.entity.OpenMarket;
import com.dongwu.manager.service.OpenMarketService;
/**
 * 营销工具
 * @author xyj
 *
 */
import com.dongwu.security.utils.SecurityUtils;
@Controller
@RequestMapping("/manager/openMarket")
public class OpenMarketController extends BaseController<OpenMarket, String> {
	@Autowired
	private OpenMarketService openMarketService;
	/**
	 * 保存开启记录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveOpenMarket")
	@ResponseBody
	public Result saveReturn(@RequestParam(value = "ids[]") String[] ids) {
		try {
			if (!SecurityUtils.hasRole(this.getAddRole())) {
				return Result.denyResult();
			}
			/*如果当前设备已存在开启记录则清除*/
			List<OpenMarket> oms = openMarketService.findByDeviceId(ids[0]);
			if(oms != null && ids[0] != ""){
				String[] deviceIds = new String[oms.size()];
				for (int i = 0; i < oms.size(); i++) {
					deviceIds[i] = oms.get(i).getId();
				}
				openMarketService.delete(deviceIds);	
			}
			List<OpenMarket> omList= new ArrayList<OpenMarket>();
			for(int i = 1; i<ids.length; i++){
				OpenMarket om= new OpenMarket();
				om.setDeviceId(ids[0]);
				om.setMarketId(ids[i]);
				//om.setUser(userService.findByLoginName(UserUtils.getUserLoginName()));
				omList.add(om);
			}
			baseService.batchUpdate(omList);
			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}
	/**
	 * 保存开启记录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getMarket/{deviceId}")
	@ResponseBody
	public Result getMarket(@PathVariable("deviceId") String deviceId) {
		try {
			if (!SecurityUtils.hasRole(this.getAddRole())) {
				return Result.denyResult();
			}
			return Result.successResult(openMarketService.findByDeviceId(deviceId));
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}
}
